package net.qhzw.vip.qiyu.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.qhzw.vip.qiyu.component.ServerConfig;
import net.qhzw.vip.qiyu.entity.Contract;
import net.qhzw.vip.qiyu.entity.SysContract;
import net.qhzw.vip.qiyu.model.ContractData;
import net.qhzw.vip.qiyu.model.ContractFom;
import net.qhzw.vip.qiyu.model.ContractVo;
import net.qhzw.vip.qiyu.result.JsonResult;
import net.qhzw.vip.qiyu.service.ContractService;
import net.qhzw.vip.qiyu.service.SysContractService;
import net.qhzw.vip.qiyu.service.SysElectricVehBrandService;
import net.qhzw.vip.qiyu.service.SysPostageService;
import net.qhzw.vip.qiyu.util.MyDateUtils;
import net.qhzw.vip.qiyu.util.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Controller
@Api(tags = "合同管理")
@Slf4j
public class ContractController {


    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private ServerConfig serverConfig;

    @Autowired
    private SysContractService sysContractService;

    @Autowired
    private ContractService contractService;

    @Value("${minio.endpoint}")
    private String endpoint;

    @Autowired
    private SysPostageService sysPostageService;

    @Autowired
    private SysElectricVehBrandService electricVehBrandService;

    @ApiOperation(value = "查询合同")
    @GetMapping("sys/contract")
    @ResponseBody
    public JsonResult<List<SysContract>> index() {
        Long shopId = SecurityUtils.getLoginUser().getShopId();
        List<SysContract> sysContractList = sysContractService.list(new LambdaQueryWrapper<SysContract>()
                .eq(shopId != 1, SysContract::getShopId, shopId));
        for (SysContract sysContract : sysContractList) {
            if (!StringUtils.isEmpty(sysContract.getReceiptCode())){
                sysContract.setReceiptCodes(Arrays.asList(sysContract.getReceiptCode().split(",")));
            }
        }
        return JsonResult.ok(sysContractList);
    }


    @ApiOperation(value = "查询租车售后电话")
    @GetMapping("sys/contract/getExchange")
    @ResponseBody
    public JsonResult getExchange(Long userId) {
        Map<String, String> result = sysContractService.getExchange(userId);
        return JsonResult.ok(result);
    }

    @ApiOperation(value = "修改合同")
    @PutMapping("sys/contract")
    @ResponseBody
    public JsonResult addContract(@RequestBody SysContract sysContract) {
        sysContract.setModifyBy(SecurityUtils.getUserId());
        boolean isOK = false;
        if (sysContract.getId() == null) {
            Long shopId = SecurityUtils.getLoginUser().getShopId();
            sysContract.setShopId(shopId);
            isOK = sysContractService.save(sysContract);
        } else {
            isOK = sysContractService.updateById(sysContract);
        }
        if (isOK) {
            return JsonResult.ok();
        }
        return JsonResult.fail();
    }


    @ApiOperation(value = "查看注意事项")
    @GetMapping("contract/show")
    public String show() {
        return "contract-1";
    }


    /***
     * 系统调用生成合同
     * @return
     */
    @ApiOperation(value = "生成合同")
    @PostMapping("sys/contract/create")
    public String sysCreate(@RequestBody ContractData contractData, Model model) {
        log.info("系统调用生成合同: {}", JSON.toJSONString(contractData));
        model.addAttribute("contractData", contractData);
        return "contract";
    }


    @ApiOperation(value = "提交合同")
    @PostMapping("contract/submit")
    @ResponseBody
    public JsonResult submit(Model model, @RequestBody ContractFom contractFom, HttpServletRequest request) {
        Long userId = SecurityUtils.getUserId();
        ContractVo contractVo = contractService.find(userId);
        //查询站点地址
        if (!StringUtils.isEmpty(contractFom.getCommunityId())) {
            String address = contractService.findAddressById(contractFom.getCommunityId());
            contractVo.setCosigned(address);
        }
        contractVo.setLeaseForm("天");
        contractVo.setLeaseTrm(30);
        contractVo.setTerminationDate(contractFom.getTerminationDate());
        contractVo.setLeaseStartDate(MyDateUtils.getCurDt());

        contractVo.setSign(contractFom.getSign());
        model.addAttribute("contract", contractVo);
        //保存合同
        Long id = contractService.addContract(contractFom, request);
        if (id == null) {
            return JsonResult.fail();
        }
        return JsonResult.ok(id);
    }


    @ApiOperation(value = "根据id查询提交的合同")
    @GetMapping("contract/{id}")
    @ResponseBody
    public JsonResult<Contract> getContract(@PathVariable Long id) {
        Contract contract = contractService.getById(id);
        return JsonResult.ok(contract);
    }


    @ApiOperation(value = "分页查询提交的合同")
    @GetMapping("contract/findBYPage")
    @ResponseBody
    public JsonResult<Page<Contract>> findBYPage(Page<Contract> page, String keywords, Byte status) {
        Page<Contract> contractPage = contractService.findBYPage(page, keywords, status);
        return JsonResult.ok(contractPage);
    }



}
